package com.weixin.paleituo.fragment;

import android.app.Dialog;
import android.content.Context;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.AllOrderRecycleAdapter;
import com.weixin.paleituo.annotation.OrderStatusType;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.LazyBaseFragment;
import com.weixin.paleituo.bean.GoodsOrderBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.StoreListBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.AllOrderEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.YRecycleview;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Author yichao
 * Time  2018/4/7 17:14
 * Dest 所有订单
 */
public class AllOrderFragment extends LazyBaseFragment{
    @BindView(R.id.yrecycleview_fragment_awaitpayfor)
    YRecycleview mYrecycleviewFragmentAwaitpayfor;
    private LoadingPagerHead mLoadingPagerHead;
    private List<StoreListBean> mStoreListBeans=new ArrayList<>();
    private AllOrderRecycleAdapter mAllOrderRecycleAdapter;
    private int curentPag=1;
    private String orderStatus="0";
    private boolean mIsPrepared;
    private Dialog mLoadingDialog;
    private boolean isFirst=true;



    @Override
    public View initView(Context context) {

        if (mLoadingPagerHead==null){
        mLoadingPagerHead = new LoadingPagerHead(mContext) {
            @Override
            protected void close() {
            }
            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(mContext, R.layout.fragment_awaitpayfor);
            }
            @Override
            protected void reLoading() {
                retry();
            }
        };
          }
        return mLoadingPagerHead;
    }



    /**
     * 重试
     */
    private void retry() {
        curentPag=1;
        Observable<StatusCode<List<GoodsOrderBean>>> orderListObservable = ApiUtils.getApi().getOrderList(BaseApplication.getToken(), BaseApplication.getUserId(), orderStatus, 1, Contans.rows);
        HttpUtil.getInstance().toSubscribe(orderListObservable, new ProgressSubscriber<List<GoodsOrderBean>>(mContext) {
            @Override
            protected void _onNext(StatusCode<List<GoodsOrderBean>> listStatusCode) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                List<GoodsOrderBean> goodsOrderBeans = listStatusCode.getData();
                if (goodsOrderBeans!=null&&goodsOrderBeans.size()>0){
                    mStoreListBeans.clear();
                    for (GoodsOrderBean goodsOrderBean:goodsOrderBeans){
                        for (StoreListBean storeListBean:goodsOrderBean.getStoreList()){
                            mStoreListBeans.add(storeListBean);
                        }
                    }
                    mAllOrderRecycleAdapter.notifyDataSetChanged();
                    mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);

                }else {
                    mLoadingPagerHead.showPagerView(Contans.STATE_EMPTY);
                }
            }

            @Override
            protected void _onError(String message) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                mLoadingPagerHead.showPagerView(Contans.STATE_ERROR);
                ToastUtils.makeText(message);
            }
        },"",lifecycleSubject,false,true);
    }
    @Override

    protected void lazyLoad() {
        if(!mIsPrepared || !isVisible) {
            return;
        }
        load();
    }

    /**
     * 懒加载数据
     */
    private void load() {

        if (mLoadingDialog==null){
            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(getActivity(), "");
        }
        LoadingDialogUtils.show(mLoadingDialog);
        retry();

    }
    /**
     *
     * @param allOrderEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void orderSureGoodsEvent(AllOrderEvent allOrderEvent){
        final int positon = allOrderEvent.getPositon();
        int type = allOrderEvent.getType();
        /**收货*/
        if (type==Contans.SURE_ACCEPT_GOODS_TYPE){
            final String orderDetailId = mStoreListBeans.get(positon).getOrderDetailId();
            if (!StringUtils.isEmpty(orderDetailId)){
                Observable<StatusCode<Object>> statusCodeObservable = ApiUtils.getApi().getGoods(
                        BaseApplication.getToken(),
                        BaseApplication.getUserId(),
                        Integer.valueOf(orderDetailId)).compose(RxHelper.getObservaleTransformer())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                if (mLoadingDialog == null) {
                                    mLoadingDialog = LoadingDialogUtils.createLoadingDialog(mContext, "");
                                }
                                LoadingDialogUtils.show(mLoadingDialog);
                            }
                        }).subscribeOn(AndroidSchedulers.mainThread());

                HttpUtil.getInstance().toSubscribe(statusCodeObservable,
                        new ProgressSubscriber<Object>(mContext) {
                            @Override
                            protected void _onNext(StatusCode<Object> statusCode) {
                                LoadingDialogUtils.closeDialog(mLoadingDialog);


                                mStoreListBeans.remove(positon);
                                mAllOrderRecycleAdapter.notifyDataSetChanged();


                            }
                            @Override
                            protected void _onError(String message) {
                                LoadingDialogUtils.closeDialog(mLoadingDialog);
                                ToastUtils.makeText(message);
                            }
                        }, "", lifecycleSubject, false, true);

            }

        } else if(type==Contans.DELETE_ORDER_TYPE){

            StoreListBean storeListBean = mStoreListBeans.get(positon);
            int id = storeListBean.getId();

            int detailId = storeListBean.getDetailId();


            int orderStatus = storeListBean.getOrderStatus();

            String sign="";
                if (orderStatus== OrderStatusType.CANCEL){
                    sign="1";
                }else if (orderStatus==OrderStatusType.COMPLETE||orderStatus==OrderStatusType.FINISH){

                    sign="2";
                }
            Observable<StatusCode<Object>> statusCodeObservable = ApiUtils.getApi().deleteOrders(BaseApplication.getToken(), BaseApplication.getUserId(), id + "", detailId + "", sign)
                    .compose(RxHelper.getObservaleTransformer())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            if (mLoadingDialog == null) {
                                mLoadingDialog = LoadingDialogUtils.createLoadingDialog(mContext, "");
                            }
                            LoadingDialogUtils.show(mLoadingDialog);
                        }
                    }).subscribeOn(AndroidSchedulers.mainThread());;
            HttpUtil.getInstance().toSubscribe(statusCodeObservable, new ProgressSubscriber<Object>(mContext) {
                @Override
                protected void _onNext(StatusCode<Object> objectStatusCode) {
                    LoadingDialogUtils.closeDialog(mLoadingDialog);

                 mStoreListBeans.remove(positon);
                    mAllOrderRecycleAdapter.notifyDataSetChanged();


                }

                @Override
                protected void _onError(String message) {
                    LoadingDialogUtils.closeDialog(mLoadingDialog);

                    ToastUtils.makeText(message);

                }
            },"",lifecycleSubject,false,true);
        }








    }




    @Override
    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);
        mIsPrepared = true;
        mStoreListBeans.clear();
        mAllOrderRecycleAdapter = new AllOrderRecycleAdapter(mContext,mStoreListBeans);
        mYrecycleviewFragmentAwaitpayfor.setLayoutManager(new LinearLayoutManager(mContext));
        mYrecycleviewFragmentAwaitpayfor.setItemAnimator(new DefaultItemAnimator());
        mYrecycleviewFragmentAwaitpayfor.setAdapter(mAllOrderRecycleAdapter);

        mYrecycleviewFragmentAwaitpayfor.setRefreshAndLoadMoreListener(new YRecycleview.OnRefreshAndLoadMoreListener() {
            @Override
            public void onRefresh() {


                Observable<StatusCode<List<GoodsOrderBean>>> orderListObservable = ApiUtils.getApi().getOrderList(BaseApplication.getToken(), BaseApplication.getUserId(), orderStatus, 1, Contans.rows);
                HttpUtil.getInstance().toSubscribe(orderListObservable, new ProgressSubscriber<List<GoodsOrderBean>>(mContext) {
                    @Override
                    protected void _onNext(StatusCode<List<GoodsOrderBean>> listStatusCode) {
                        List<GoodsOrderBean> goodsOrderBeans = listStatusCode.getData();
                        mYrecycleviewFragmentAwaitpayfor.setReFreshComplete();
                        if (goodsOrderBeans!=null&&goodsOrderBeans.size()>0){
                            mStoreListBeans.clear();
                            for (GoodsOrderBean goodsOrderBean:goodsOrderBeans){
                                for (StoreListBean storeListBean:goodsOrderBean.getStoreList()){
                                    mStoreListBeans.add(storeListBean);

                                }
                            }
                            curentPag=1;
                            mAllOrderRecycleAdapter.notifyDataSetChanged();

                        }else {
                            ToastUtils.makeText("刷新失败");
                        }

                    }

                    @Override
                    protected void _onError(String message) {
                        mYrecycleviewFragmentAwaitpayfor.setReFreshComplete();
                        ToastUtils.makeText(message);


                    }
                },"",lifecycleSubject,false,true);


            }

            @Override
            public void onLoadMore() {

                Observable<StatusCode<List<GoodsOrderBean>>> orderListObservable = ApiUtils.getApi().getOrderList(BaseApplication.getToken(), BaseApplication.getUserId(), orderStatus, curentPag+1, Contans.rows);
                HttpUtil.getInstance().toSubscribe(orderListObservable, new ProgressSubscriber<List<GoodsOrderBean>>(mContext) {
                    @Override
                    protected void _onNext(StatusCode<List<GoodsOrderBean>> listStatusCode) {
                        List<GoodsOrderBean> goodsOrderBeans = listStatusCode.getData();
                        mYrecycleviewFragmentAwaitpayfor.setloadMoreComplete();
                        if (goodsOrderBeans!=null&&goodsOrderBeans.size()>0){

                            for (GoodsOrderBean goodsOrderBean:goodsOrderBeans){
                                for (StoreListBean storeListBean:goodsOrderBean.getStoreList()){
                                    mStoreListBeans.add(storeListBean);

                                }
                            }

                            mAllOrderRecycleAdapter.notifyDataSetChanged();
                            curentPag+=1;

                        }else {
                            ToastUtils.makeText("没有更多数据了");
                        }
                    }
                    @Override
                    protected void _onError(String message) {
                        mYrecycleviewFragmentAwaitpayfor.setloadMoreComplete();
                        ToastUtils.makeText(message);
                    }
                },"",lifecycleSubject,false,true);


            }
        });

        retry();
    }


    @Override
    public void onResume() {
        super.onResume();

        if (isFirst){

            isFirst=false;

        }else {

if (isVisible){
            load();

}

        }


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        mLoadingDialog=null;
        mIsPrepared=false;
        isFirst= true;
    }

}
